package com.apes.fn.server.servicePlan.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.server.servicePlan.model.ClientInvoiceRules;
import com.apes.fn.server.servicePlan.repository.ClientInvoiceRulesRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @program:
 * @description:
 * @author: lws
 * @create: 2023/3/20 15:20
 **/
@Service
public class ClientInvoiceRulesService extends DomainService {

    @Autowired
    private ClientInvoiceRulesRepository clientInvoiceRulesRepository;

    public ClientInvoiceRules save(SimpleRequest request) {
        ClientInvoiceRules clientInvoiceRules = request.getO(ClientInvoiceRules.class);
        checkClientInvoiceRules(clientInvoiceRules);
        return saveAndFlush(clientInvoiceRules);
    }

    public ClientInvoiceRules update(SimpleRequest request) {
        ClientInvoiceRules clientInvoiceRules = request.getO(ClientInvoiceRules.class);
        checkClientInvoiceRules(clientInvoiceRules);
        return saveAndFlush(clientInvoiceRules);
    }

    public void delete(SimpleRequest request){
        ClientInvoiceRules clientInvoiceRules = request.getO(ClientInvoiceRules.class);
        clientInvoiceRulesRepository.delete(clientInvoiceRules);
    }

    private ClientInvoiceRules saveAndFlush(ClientInvoiceRules clientInvoiceRules) {
        clientInvoiceRules.getClientInvoiceRulesItems().forEach(clientInvoiceRulesItem -> {
            clientInvoiceRulesItem.setClientInvoiceRules(clientInvoiceRules);
        });
        return clientInvoiceRulesRepository.saveAndFlush(clientInvoiceRules);
    }

    private void checkClientInvoiceRules(ClientInvoiceRules clientInvoiceRules) {
        Map distinct = new HashMap();
        if (clientInvoiceRules.getClientInvoiceRulesItems().isEmpty()) throw new RuntimeException("可服务门店不能为空！");
        clientInvoiceRules.getClientInvoiceRulesItems().stream().forEach(clientInvoiceRulesItem -> {
            Assert.isTrue(!distinct.containsKey(clientInvoiceRulesItem.getDept().getId()), "门店" + clientInvoiceRulesItem.getDept().getId() + "重复！");
            distinct.put(clientInvoiceRulesItem.getDept().getId(), "dept");
            Assert.isTrue(!(clientInvoiceRulesItem.getCrossSingleRatio() > 1), "扣收费用比率不允许大于1！");
        });
    }


    /**
     * 查找单位客户规则
     *
     * @param dept       单据门店
     * @param unitClient 单位客户
     * @return ClientInvoiceRules
     */
    public ClientInvoiceRules findClientInvoiceRules(Dept dept, PartyRole unitClient) {
        // 第一步：查询当前门店是否开票公司
        ClientInvoiceRules clientInvoiceRules = clientInvoiceRulesRepository.findAll(JpaDsl.toCriteriaByEq("dept", dept, "customer", unitClient))
                .stream().findFirst().orElse(null);
        if (Objects.isNull(clientInvoiceRules)) {
            // 第二步：当前门店非开票公司
            clientInvoiceRules = clientInvoiceRulesRepository.findClientInvoiceRulesByItemDept(dept.getId(), unitClient.getId());
        }
        return clientInvoiceRules;
    }

    /**
     * 服务方案-异业合作页面，批量选择客户，查询下拉框
     * @param request
     * @return
     */
    public Page searchUnitClient(SimpleRequest request){
        JSONObject jo = request.getJO();
        JSONArray filters = jo.getJSONObject("group").getJSONArray("filters");
        JSONObject param = new JSONObject();
        filters.forEach(filter->{
            JSONObject filterJO = (JSONObject) filter;
            param.put(filterJO.getString("field"),filterJO.getString("value"));
        });
        checkParam(param);  // 检查入参
        Page<ClientInvoiceRules> result = clientInvoiceRulesRepository.findByUnitClient(param.getString("id"),
                param.getString("name"),
                param.getString("belongDeptId"),
                PageRequest.of(request.get("page"), request.get("size")));
        return result;
    }

    private void checkParam(JSONObject param){
        Assert.isTrue(param.containsKey("id") && param.getString("id") != null, "缺少参数异常！");
        Assert.isTrue(param.containsKey("name") && param.getString("name") != null, "缺少参数异常！");
        Assert.isTrue(param.containsKey("belongDeptId") && param.getString("belongDeptId") != null, "缺少参数异常！");
    }
}
